package com.maimang.platform.config;

import com.maimang.platform.common.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Rocky
 * @version 1.0.0
 * @类名 LoginInterceptor
 * @描述 <br>登录拦截器</br>
 * @日期 2019-05-01
 * @email jintaozhao@qq.com
 */
@Controller
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String basePath = request.getContextPath();
		String path = request.getRequestURI();

		// 是否进行拦截
		if (!doLoginInterceptor(path, basePath)) {
			return true;
		}

		//如果登录了，会把用户信息存进session
		HttpSession session = request.getSession();
		List<SysUser> users = (List<SysUser>) session.getAttribute("userList");
		if (users != null) {
			String requestType = request.getHeader("X-Requested-With");
			System.out.println(requestType);
			if (requestType != null && requestType.equals("XMLHttpRequest")) {
				response.setHeader("sessionstatus", "timeout");
//				response.setHeader("basePath",request.getContextPath());
				response.getWriter().print("LoginTimeout");
				return false;
			} else {
				logger.info("尚未登录，跳转到登录界面");
				response.sendRedirect(request.getContextPath() + "login");
			}
			logger.info("用户已登录,userName:" + users.get(0).getUserName());
			return false;
		}
		return super.preHandle(request, response, handler);
	}

	private boolean doLoginInterceptor(String path, String basePath) {
		path = path.substring(basePath.length());
		Set<String> notLoginPaths = new HashSet<>();
		//设置不进行登录拦截的路径：登录注册和验证码
		notLoginPaths.add("/");
		notLoginPaths.add("/signin");
		notLoginPaths.add("/login");
		notLoginPaths.add("/register");
		notLoginPaths.add("/captcha/captchaImage");
		notLoginPaths.add("/captcha");
		notLoginPaths.add("/sys/logout");
		notLoginPaths.add("/loginTimeout");
		notLoginPaths.add("/favicon.ico**");
		notLoginPaths.add("/platform.png**");
		notLoginPaths.add("/css");
		notLoginPaths.add("/docs");
		notLoginPaths.add("/fonts");
		notLoginPaths.add("/images");
		notLoginPaths.add("/ajax");
		notLoginPaths.add("/js");
		notLoginPaths.add("/platform");
		notLoginPaths.add("/druid");
		notLoginPaths.add("/open"); // 不需要权限对外开放的接口
		notLoginPaths.add("/crm"); // jwt权限接口，拦截器处理WebConfig类
		notLoginPaths.add("/dingtalk"); // jwt权限接口，拦截器处理WebConfig类

		if (notLoginPaths.contains(path))
			return false;
		return true;
	}
}
